﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using PlaywrightSharp;

namespace XiaoQuPriceTrendCrawler
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("下载 playwright");
            await Playwright.InstallAsync();
            using var playwright = await Playwright.CreateAsync();
            await using var browser = await playwright.Chromium.LaunchAsync(headless: true);

            var page = await browser.NewPageAsync();
            var cityNames = new List<string>
            {
                "北京",
                "天津",
                "上海",
                "南京",
                "苏州",
                "济南",
                "青岛",
                "深圳",
                "成都"
            };
            Console.WriteLine("开始抓取指定城市home页");

            await page.GoToAsync("https://esf.fang.com/newsecond/esfcities.aspx");
            var cityElements = await page.QuerySelectorAllAsync("#c01 a");
            var cityElementArray = cityElements.ToArray();
            for (var i = 0; i < cityElementArray.Count(); i++)
            {
                var name = await cityElementArray[i].GetInnerTextAsync();
                var homeUrl = await cityElementArray[i].GetAttributeAsync("href");
                if (cityNames.Contains(name))
                    Console.WriteLine($"{name} {homeUrl}");
            }

            Console.WriteLine("Export completed");
        }

        /// <summary>
        /// 校验是否出现验证码
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static async Task CheckValidCode(Page page)
        {
            // 判断是否出现滑动验证码页
            var verifyPage = await page.QuerySelectorAsync("#verify_page");
            if (verifyPage != null)
            {
                Console.WriteLine("爬取数据太频繁，出现滑块验证码，请在浏览器上手工校验通过后，点击任意键继续：");
                var input = Console.ReadLine();
                await page.ReloadAsync();
            }
        }
    }
}